import json
import pypinyin

from django.shortcuts import render
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import status
from django.db import models
from django.core.paginator import Paginator
from django.db.models.functions import ExtractMonth
from django.db.models import Count

from user.models import *
from flow.models import *
from flow.serializer import *
from user.serializer import *
from util.jwt_token import check_login
from util.qiniuyun_token import qiniu_token
from .serializer import *

# EXPLAIN


# 分页函数
def pag(self, userinfo, pag_size, pagination):
    paginator = Paginator(userinfo, pag_size)

    page = paginator.page(pagination)

    return page.object_list


def res(date):
    if len(date) == 0:
        return None
    for i in date:
        menu = MenuModel.objects.filter(menu=i["id"], is_delete=False).order_by("menu_sort").all()
        menu = MenuSer(menu, many=True)
        menu = json.loads(json.dumps(menu.data))
        print("date", date)
        i["menu"] = res(menu)
    return date


class UserView(ViewSet):
    # 获取用户信息
    # @check_login
    def user_list(self, request):
        try:
            # 接收一页展示多少条数据
            pag_size = request.data.get("pag_size")
            # # 展示的页码
            pagination = request.data.get("pagination")

            user = UserModel.objects.filter(is_delete=False)

            page = pag(self, user, pag_size, pagination)
            ser = UserSer(page, many=True)
            user_set = json.loads(json.dumps(ser.data))

            list = []
            for i in user_set:
                # 查询出职位
                user_list = PositionModel.objects.filter(id=i["position"]).first()
                # 查询出职级
                rank = RankModel.objects.filter(id=user_list.rank_id).first()
                # 查询出部门
                dept = DeptModel.objects.filter(id=user_list.dept_id).first()
                # 查询出角色
                role = PositionRoleModel.objects.filter(position=user_list.id).first()
                role_list = RoleModel.objects.filter(id=role.role_id).first()

                i["rank_id"] = rank.id
                i["rank"] = rank.name
                i["section_id"] = dept.id
                i["section"] = dept.name
                i["role"] = role_list.name
            list.extend(user_set)
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": list})
        except Exception as e:
            print("获取失败的原因", e)
            return Response({"code": 500, "msg": "服务器错误"})

    # 搜索用户
    @check_login
    def searchs(self, request):
        name = request.data.get("name")
        mobile = request.data.get("mobile")
        position = request.data.get("position")

        try:
            positions = PositionModel.objects.all()

            if position:
                positions = positions.filter(name=position)
            user_list = []
            for j in positions:
                user_set = UserModel.objects.filter(position_id=j.id).all()

                if name:
                    user_set = user_set.filter(name=name)
                if mobile:
                    user_set = user_set.filter(mobile=mobile)
                ser = UserSer(user_set, many=True)
                user_set = json.loads(json.dumps(ser.data))
                for i in user_set:
                    rank = RankModel.objects.filter(id=j.rank_id).first()
                    dept = DeptModel.objects.filter(id=j.dept_id).first()
                    i['rank_id'] = rank.id
                    i["rank"] = rank.name
                    i["section_id"] = dept.id
                    i["section"] = dept.name
                user_list.extend(user_set)
            return Response({"code": status.HTTP_200_OK, "msg": "查询成功", "data": user_list})
        except Exception as e:
            print("查询失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "查询失败"})

    # 修改员工个人信息
    # @check_login
    def upuser(self, request, pk):
        user = UserModel.objects.filter(id=pk, is_delete=False).first()
        print("user", user)
        name = request.data.get("name")
        account = request.data.get("account")
        mobile = request.data.get("mobile")
        role = request.data.get("role")
        rank = request.data.get("rank")
        department = request.data.get("department")

        try:
            user = UserModel.objects.filter(name=name, is_delete=False).exclude(id=pk).count()
            if user != 0:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '此用户名已经存在，请重新输入'})

            user = UserModel.objects.filter(account=account, is_delete=False).exclude(id=pk).count()
            if user != 0:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '此账号已经存在，请重新输入'})

            user = UserModel.objects.filter(id=pk, is_delete=False)
            if not user:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "用户不存在"})

            if name:
                user.update(name=name)
            if account:
                user.update(account=account)
            if mobile:
                user.update(mobile=mobile)
            return Response({'code': 200, 'msg': '修改成功'})
        except Exception as e:
            print("修改失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "修改失败"})

    # 获取单个用户信息
    # @check_login
    def user_info(self, request, pk):
        try:
            user = UserModel.objects.filter(id=pk, is_delete=False).first()
            print("user", user)
            # ser = UserSer(self._cuser)
            ser = UserSer(user)
            user_lst = json.loads(json.dumps(ser.data))

            user = UserModel.objects.filter(id=user_lst['id'], is_delete=0).first()

            position = PositionModel.objects.filter(id=user.position_id, is_delete=False).first()

            # 查询出职级
            rank = RankModel.objects.filter(id=position.rank_id, is_delete=False).first()
            rank_list = RankSer(rank)

            # 查询出部门
            dept = DeptModel.objects.filter(id=position.dept_id, is_delete=False).first()
            dept_list = DeptSer(dept)

            # 查询出角色
            role = PositionRoleModel.objects.filter(position_id=user.position_id).first()
            role_list = RoleModel.objects.filter(id=role.role_id).first()

            data = {
                "name": ser.data['name'],
                "account": ser.data['account'],
                "mobile": ser.data['mobile'],
                "position": ser.data['position_name'],
                "rank": rank_list.data['name'],
                "dept": dept_list.data['name'],
                "role": role_list.name
            }
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": data})
        except Exception as e:
            print("失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 推荐账号
    def nominate_account(self, request):
        account = request.data.get("account")
        account = ''.join(pypinyin.lazy_pinyin(account))
        num = UserModel.objects.filter(account=account).count()
        if num > 0:
            num_ = str(num + 1)
            account = account + num_
            return Response({'code': status.HTTP_200_OK, 'msg': '推荐账号成功', 'account': account})
        else:
            account = account + '1'
            return Response({'code': status.HTTP_200_OK, 'msg': '推荐账号成功', 'account': account})

    # 七牛云
    def qiniuyun(self, request):
        try:
            token = qiniu_token()
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "token": token})

        except Exception as e:
            print("错误", e)
            return Response({"code": 500, "msg": "失败"})


# 获取登录日志
class LogsView(ViewSet):

    # 获取登录日志
    @check_login
    def logs_list(self, request):
        try:
            # 接收一页展示多少条数据
            pag_size = request.data.get("pag_size")
            # 展示的页码
            pagination = request.data.get("pagination")

            logs = ConLogModel.objects.all()
            page = pag(self, logs, pag_size, pagination)
            ser = ConLogSer(page, many=True)
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": ser.data})
        except Exception as e:
            print("获取失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 搜索
    @check_login
    def search(self, request):
        # 接收一页展示多少条数据
        pag_size = request.data.get("pag_size")
        # 展示的页码
        pagination = request.data.get("pagination")
        account = request.data.get("account")

        try:
            user = UserModel.objects.filter(account=account, is_delete=False).first()
            con = ConLogModel.objects.filter(user_id=user.id).all()
            page = pag(self, con, pag_size, pagination)
            ser = ConLogSer(page, many=True)
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": ser.data})
        except Exception as e:
            print("搜索失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "搜索失败"})


# 首页
class HomeView(ViewSet):

    # 获取员工生日数据
    @check_login
    def user_birthday(self, request):
        try:
            user = UserModel.objects.annotate(month=ExtractMonth('birthday')).values('month').annotate(num=Count('name'))

            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": user})
        except Exception as e:
            print("获取失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 获取员工地区
    @check_login
    def user_area(self, request):
        try:
            user = UserModel.objects.values('attribution').annotate(num=Count('attribution'))
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": user})
        except Exception as e:
            print("获取失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 获取员工数据
    @check_login
    def user_list(self, request):
        try:

            # 获取全部
            user_list = UserModel.objects.filter(is_delete=False).count()
            print("user-list", user_list)

            # 获取待入职
            user_entry = UserModel.objects.filter(is_staff=0).count()
            print("----", user_entry)

            # 获取实习生
            user_intern = UserModel.objects.filter(is_staff=1).count()
            print("----", user_intern)

            # 获取正式员工
            user_staff = UserModel.objects.filter(is_staff=2).count()
            print("----", user_staff)

            # 获取代离职
            user_quit = UserModel.objects.filter(is_staff=3).count()
            print("----", user_quit)

            # 获取待转正
            user_positive = UserModel.objects.filter(is_staff=4).count()
            print("----", user_positive)

            date = {
                # 正式员工
                "count":user_list,
                # 正式员工
                "formal": user_staff,
                # 实习生
                "exercitation": user_intern,
                # 待入职
                "awaitrding": user_entry,
                # 待离职
                "awaitdimission": user_quit,
                # 待转正
                "awaitPositive": user_positive
            }

            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": date})
        except Exception as e:
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 获取所有待办事项
    @check_login
    def todos_list(self, request):
        try:
            flow_node = FlowNodeModel.objects.filter(is_delete=False, vettsatus=0)
            flow_node_ser = FlowNodeSer(flow_node, many=True).data

            for i in flow_node_ser:
                # 先查找出用户
                user = UserModel.objects.filter(id=i.get("id"))
                user_ser = UserSer(user, many=True)
                # 根据用户查找职位 然后在查找部门
                for user in user_ser.data:
                    position_id = user.get("position")
                    position = PositionModel.objects.filter(id=position_id)
                    position_ser = PositionSer(position, many=True)
                    print(position_ser.data)
                    for j in position_ser.data:
                        i["department"] = j.get("dept_name")
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": flow_node_ser})
        except Exception as e:
            print("获取失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})


# 部门
class DeptView(ViewSet):

    # 获取所有部门
    @check_login
    def dept_list(self, request):

        # 接收一页展示多少条数据
        pag_size = request.data.get("pag_size")
        # 展示的页码
        pagination = request.data.get("pagination")
        try:
            dept_list = DeptModel.objects.all()
            page = pag(self, dept_list, pag_size, pagination)
            ser = DeptSer(page, many=True)
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": ser.data})
        except Exception as e:
            print("获取所有部门失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 删除部门
    # @check_login
    def dept_del(self, request, pk):
        try:

            lst = DeptModel.objects.filter(id=pk, is_delete=False)
            if not lst:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此部门 "})

            lst.update(is_delete=True)
            return Response({"code": status.HTTP_200_OK, "msg": "删除成功"})

        except Exception as e:
            print("删除失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "删除失败"})

    # 修改部门
    # @check_login
    def dept_update(self, request, pk):
        name = request.data.get("name")
        remarks = request.data.get("remark")

        try:
            lst = DeptModel.objects.filter(id=pk, is_delete=False)

            if not lst:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此部门 "})

            if name:
                lst.update(name=name)
            if remarks:
                lst.update(remarks=remarks)
            return Response({'code': status.HTTP_200_OK, 'msg': '修改成功'})
        except Exception as e:
            print(str(e))
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '修改失败'})

    # 添加部门
    @check_login
    def dept_add(self, request):
        name = request.data.get("name")
        remarks = request.data.get("remark")

        try:
            dept = DeptModel.objects.filter(name=name, is_delete=False).first()
            if dept:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "部门已经存在"})

            DeptModel.objects.create(name=name, remarks=remarks)
            return Response({"code": status.HTTP_200_OK, "msg": "添加部门成功"})
        except Exception as e:
            print("添加失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "添加部门失败"})

    # 获取单个部门
    # @check_login
    def dept_single(self, request, pk):
        try:
            dept = DeptModel.objects.filter(id=pk, is_delete=False).first()
            print("rank", dept)
            ser = DeptSer(dept)
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": ser.data})
        except Exception as e:
            print("获取部门失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 搜索部门
    def dept_search(self, request):
        name = request.data.get("name")
        try:
            dept = DeptModel.objects.filter(name=name, is_delete=False).first()
            print("dept", dept)

            if not dept:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此部门 "})

            ser = DeptSer(dept)

            return Response({"code": status.HTTP_200_OK, "msg": "搜索成功", "data": ser.data})
        except Exception as e:
            print("搜索部门失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "搜索失败"})


# 职级
class RankView(ViewSet):

    # 获取所有职级
    @check_login
    def rank_list(self, request):
       try:
           # 接收一页展示多少条数据
           pag_size = request.data.get("pag_size")
           # 展示的页码
           pagination = request.data.get("pagination")

           rank = RankModel.objects.all()
           page = pag(self, rank, pag_size, pagination)
           ser = RankSer(page, many=True)
           return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": ser.data})
       except Exception as e:
            print("获取所有职级失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 新增职级
    @check_login
    def rank_add(self, request):
        name = request.data.get("rankname")
        try:
            rank = RankModel.objects.filter(name=name, is_delete=False).first()

            if rank:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "职级已经存在"})

            RankModel.objects.create(name=name)
            return Response({"code": status.HTTP_200_OK, "msg": "新增职级成功"})
        except Exception as e:
            print("新增职级失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "新增职级失败"})

    # 获取单个职级
    # @check_login
    def rank_single(self, request, pk):
        try:
            rank = RankModel.objects.filter(id=pk, is_delete=False).first()
            print("rank", rank)
            ser = RankSer(rank)
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": ser.data})
        except Exception as e:
            print("获取职级失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 修改职级
    # @check_login
    def rank_update(self, request, pk):
        try:
            name = request.data.get("rankname")
            rank = RankModel.objects.filter(id=pk, is_delete=False)
            print("rank", rank)

            if not rank:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此职级 "})

            if name:
                rank.update(name=name)
            return Response({"code": status.HTTP_200_OK, "msg": "修改成功"})
        except Exception as e:
            print("修改职级失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "修改失败"})

    # 删除职级
    # @check_login
    def rank_delete(self, request, pk):
        try:
            rank = RankModel.objects.filter(id=pk, is_delete=False)
            print("rank", rank)

            if not rank:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此职级 "})

            rank.update(is_delete=True)
            return Response({"code": status.HTTP_200_OK, "msg": "删除成功"})
        except Exception as e:
            print("删除职级失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "删除失败"})

    # 搜索职级
    @check_login
    def rank_search(self, request):
        name = request.data.get("name")
        try:
            rank = RankModel.objects.filter(name=name, is_delete=False).first()
            print("rank", rank)

            if not rank:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此职级 "})

            ser = RankSer(rank)

            return Response({"code": status.HTTP_200_OK, "msg": "搜索成功", "data": ser.data})
        except Exception as e:
            print("搜索职级失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "搜索失败"})


# 职位
class PositionView(ViewSet):

    # 获取所有职位
    @check_login
    def position_user(self, request):
        try:
            position = PositionModel.objects.all()
            # 接收一页展示多少条数据
            pag_size = request.data.get("pag_size")
            # 展示的页码
            pagination = request.data.get("pagination")
            page = pag(self, position, pag_size, pagination)
            ser = PositionSer(page, many=True)
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": ser.data})
        except Exception as e:
            print("获取职位失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 新增职位
    @check_login
    def position_add(self, request):
        name = request.data.get("mentname")
        dept = request.data.get("dept")
        rank = request.data.get("rank")
        try:
            lst = PositionModel.objects.filter(name=name, is_delete=False)

            if lst:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "职位已经存在"})

            dept = DeptModel.objects.filter(name=dept).first()
            rank = RankModel.objects.filter(name=rank).first()

            lst = PositionModel.objects.create(name=name, dept_id=dept.id, rank_id=rank.id)
            return Response({"code": status.HTTP_200_OK, "msg": "新增职位成功"})
        except Exception as e:
            print("新增职位失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "新增职位失败"})

    # 获取单个职位
    # @check_login
    def position_single(self, request, pk):
        try:
            lst = PositionModel.objects.filter(id=pk, is_delete=False).first()
            print("lst", lst)
            ser = PositionSer(lst)
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": ser.data})
        except Exception as e:
            print("获取职位失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 修改职位
    # @check_login
    def position_update(self, request, pk):
        try:
            name = request.data.get("mentname")
            lst = PositionModel.objects.filter(id=pk, is_delete=False)
            print("lst", lst)

            if not lst:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此职位 "})

            if name:
                lst.update(name=name)
            return Response({"code": status.HTTP_200_OK, "msg": "修改成功"})
        except Exception as e:
            print("修改职位失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "修改失败"})

    # 删除职位
    # @check_login
    def position_delete(self, request, pk):
        try:
            rank = PositionModel.objects.filter(id=pk, is_delete=False)
            print("rank", rank)

            if not rank:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此职位 "})

            rank.update(is_delete=True)
            return Response({"code": status.HTTP_200_OK, "msg": "删除成功"})
        except Exception as e:
            print("删除职位失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "删除失败"})

    # 搜索职位
    @check_login
    def position_search(self, request):
        name = request.data.get("name")
        try:
            lst = PositionModel.objects.filter(name=name, is_delete=False).first()
            print("lst", lst)

            if not lst:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此职位"})

            ser = PositionSer(lst)

            return Response({"code": status.HTTP_200_OK, "msg": "搜索成功", "data": ser.data})
        except Exception as e:
            print("搜索职位失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "搜索失败"})


# 获取操作日志
class ULogView(ViewSet):

    # 获取所有操作日志
    @check_login
    def ulog_list(self, request):
        try:
            # 接收一页展示多少条数据
            pag_size = request.data.get("pag_size")
            # 展示的页码
            pagination = request.data.get("pagination")

            lst = ULogModel.objects.all()
            print("lst", lst)

            page = pag(self, lst, pag_size, pagination)
            ser = ULogSer(page, many=True)
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": ser.data})
        except Exception as e:
            print("获取失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 搜索操作日志
    @check_login
    def search(self, request):
        # 接收一页展示多少条数据
        pag_size = request.data.get("pag_size")
        # 展示的页码
        pagination = request.data.get("pagination")
        name = request.data.get("name")

        try:
            user = UserModel.objects.filter(name=name, is_delete=False).first()
            con = ULogModel.objects.filter(user_id=user.id).all()
            page = pag(self, con, pag_size, pagination)
            ser = ULogSer(page, many=True)
            return Response({"code": status.HTTP_200_OK, "msg": "搜索成功", "data": ser.data})
        except Exception as e:
            print("搜索失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "搜索失败"})


# 菜单
class MenuView(ViewSet):

    # 获取所有菜单
    @check_login
    def menu_list(self, request):
        try:
            user_id = self._cuser.id

            # 先查询用户
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()

            # 查询职位角色表
            user_role = PositionRoleModel.objects.filter(position_id=user.position_id).all()

            menu_list = []
            for i in user_role:
                lst = MenuModel.objects.filter(role_id=i.role_id, menu=None, is_delete=False).order_by("menu_sort").all()
                ser = MenuSer(lst, many=True)
                menu = json.loads(json.dumps(ser.data))
                menu = res(menu)
                menu_list.extend(menu)
            print("-----", menu_list)
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": menu_list})
        except Exception as e:
            print("获取失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 新增菜单
    @check_login
    def menu_add(self, request):
        try:
            menutype = request.data.get("menutype")
            name = request.data.get("name")
            menurl = request.data.get("menurl")
            menuimg = request.data.get("menuimg")
            remark = request.data.get("remark")
            top = request.data.get("top")

            print("数据", request.data)
            if not all([menutype, name, menurl, remark, menuimg]):
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "数据不全"})

            menu_list = MenuModel.objects.filter(name=name, is_delete=False).count()
            if menu_list != 0:
                return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "名字存在"})

            if menutype == "目录":
                MenuModel.objects.create(name=name, path=menurl, icon=menuimg, remark=remark, menu=top, role_id=self._cuser.id)
            else:
                menutype = 1
                MenuModel.objects.create(name=name, path=menurl, icon=menuimg, remark=remark, role_id=self._cuser.id)
            return Response({"code": status.HTTP_200_OK, "msg": "添加成功"})
        except Exception as e:
            print("添加失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "添加错误"})

    # 获取单个菜单
    def menu_info(self, request, pk):
        try:
            menu = MenuModel.objects.filter(id=pk, is_delete=False).first()
            ser = MenuSer(menu)
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": ser.data})
        except Exception as e:
            print("获取失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 修改菜单
    @check_login
    def menu_update(self, request, pk):
        menutype = request.data.get("menutype")
        name = request.data.get("name")
        menurl = request.data.get("menurl")
        menuimg = request.data.get("menuimg")
        remark = request.data.get("remark")

        if not all([menutype, name, menurl, menuimg, remark]):
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "数据不全"})

        menu = MenuModel.objects.filter(id=pk, is_delete=False)

        if menutype == "目录":
            menu.update(name=name, path=menurl, icon=menuimg, remark=remark, role_id=self._cuser.id)
        else:
            menutype = 1
            menu.update(name=name, path=menurl, icon=menuimg, remark=remark, role_id=self._cuser.id)
        return Response({"code": status.HTTP_200_OK, "msg": "修改成功"})

    # 删除菜单
    @check_login
    def menu_delete(self, request, pk):
        try:
            menu = MenuModel.objects.filter(id=pk, is_delete=False)
            print('menu', menu)

            if not menu:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此菜单"})

            menu.update(is_delete=True)
            return Response({"code": status.HTTP_200_OK, "msg": "删除成功"})
        except Exception as e:
            print("删除失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "删除失败"})

    # 搜索菜单
    @check_login
    def menu_search(self, request):
        try:
            name = request.data.get("name")
            menu = MenuModel.objects.filter(name=name).first()
            ser = MenuSer(menu)
            return Response({"code": status.HTTP_200_OK, "msg": "搜索成功", "data": ser.data})
        except Exception as e:
            print("搜索失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "搜索失败"})


# 角色
class RoleView(ViewSet):

    # 获取全部角色信息
    @check_login
    def role_list(self, request):
        try:
            role = RoleModel.objects.all()
            print("role", role)
            ser = RoleSer(role, many=True)
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": ser.data})
        except Exception as e:
            print("获取失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 添加角色
    @check_login
    def role_add(self, request):
        name = request.data.get("rolename")
        remarks = request.data.get("remark")
        permission = request.data.get("permission")

        if not all([name, remarks, permission]):
            return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "数据不全"})

        role = RoleModel.objects.filter(name=name, is_delete=False)
        if role:
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "此角色已经存在"})

        try:
            RoleModel.objects.create(name=name, remarks=remarks)

            role = RoleModel.objects.filter(name=name)
            role_ser = RoleSer(role, many=True).data

            for i in role_ser:
                if i.get("name") == name:
                    name = i.get("id")
                    print("name", name)
            # 查询权限数据
            permissions = PermissionModel.objects.all()
            permission_ser = PermissionSer(permissions, many=True).data
            # 循环角色并判断与传递的名字相同的角色
            for i in permission_ser:
                print('i', i.get("name"))
                if i.get("name") != permission:
                    print("角色id（现在）",  name)
                    permissiones = PermissionModel.objects.filter(name=permission, role_id=name).count()
                    if permissiones == 0:
                        PermissionModel.objects.create(role_id=name, name=permission,path=permission)
            return Response({"code": status.HTTP_200_OK, "msg": "添加成功"})
        except Exception as e:
            print("添加失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "添加失败"})

    # 获取单个角色
    def role_info(self, request, pk):
        try:
            role = RoleModel.objects.filter(id=pk, is_delete=False).first()
            ser = RoleSer(role)

            return Response({"code":status.HTTP_200_OK, "msg": "获取成功", "data": ser.data})
        except Exception as e:
            print("获取失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 修改角色
    @check_login
    def role_update(self, request, pk):
        name = request.data.get("rolename")
        remark = request.data.get("remark")
        permission = request.data.get("permission")

        if not all([name, remark]):
            return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "数据不全"})

        try:
            role = RoleModel.objects.filter(id=pk, is_delete=False)

            if not role:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "角色不存在"})

            if name:
                role.update(name=name)
            if remark:
                role.update(remarks=remark)

            # role_ser = RoleSer(role, many=True).data
            # for i in role_ser:
            #     permissiones = PermissionModel.objects.filter(role_id=i.get("id"))
            #     print("permissiones", permissiones)
            #     if permissiones != permission:
            #         permissiones.update(name=permission)

            return Response({"code": status.HTTP_200_OK, "msg": "修改成功"})

        except Exception as e:
            print("修改失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "修改失败"})

    # 删除角色
    @check_login
    def role_delete(self, request, pk):
        try:
            role = RoleModel.objects.filter(id=pk, is_delete=False)
            role.update(is_delete=True)
            return Response({"code": status.HTTP_200_OK, "msg": "删除成功"})
        except Exception as e:
            print("删除失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "删除失败"})

    # 搜索角色
    @check_login
    def rolesearch(self, request):
        name = request.data.get("rolename")

        if not all([name]):
            return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "数据不全"})
        try:
            role = RoleModel.objects.filter(name=name).first()
            ser = RoleSer(role)
            return Response({"code": status.HTTP_200_OK, "msg": "搜索成功", "data": ser.data})
        except Exception as e:
            print("搜索失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "搜索失败"})


# 权限
class PermissionView(ViewSet):

    # 获取全部权限
    @check_login
    def list(self, request):
        try:
            list = PermissionModel.objects.all()
            ser = PermissionSer(list, many=True)
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": ser.data})
        except Exception as e:
            print("获取失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})


